package com.mustafaiev.tair.mlauncher;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * @author Tair Mustafaiev
 * 
 */
public class MLauncherWidgetProvider extends AppWidgetProvider {

	public static final int FLAG_UPDATE_PHONE_STATE = 77;

	@Override
	public void onUpdate(final Context context,
			final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {

		final ComponentName me = new ComponentName(context,
				MLauncherWidgetProvider.class);

		appWidgetManager.updateAppWidget(me,
				this.doUpdate(context, appWidgetIds));
	}

	/**
	 * @param context
	 * @param appWidgetIds
	 * @return
	 */
	private RemoteViews doUpdate(final Context context, final int[] appWidgetIds) {

		final RemoteViews updateViews = new RemoteViews(
				context.getPackageName(), R.layout.widget_layout);

		final Intent intent = new Intent(context, MLauncherWidgetProvider.class);

		intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		intent.setFlags(MLauncherWidgetProvider.FLAG_UPDATE_PHONE_STATE);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

		final PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
				0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		final boolean isEnabled = this.changeMobileDataState(context, intent);

		updateViews.setOnClickPendingIntent(R.id.changeStateButton,
				pendingIntent);

		if (isEnabled) {
			updateViews.setImageViewResource(R.id.wirelessImg,
					R.drawable.antenne_on);
		} else {
			updateViews.setImageViewResource(R.id.wirelessImg,
					R.drawable.antenne_off);
		}
		Log.i("MLauncherWidgetProvider.doUpdate", "updating");

		return updateViews;
	}

	/**
	 * Enables or disables mobile data state
	 * 
	 * @param context
	 *            - {@link Context}
	 * @param intent
	 *            - {@link Intent}
	 */
	private boolean changeMobileDataState(final Context context,
			final Intent intent) {

		final MLauncherConnectivityManager manager = new MLauncherConnectivityManager(
				context);

		boolean isMobileDataEnabled = manager.isMobileDataEnabled();
		if (MLauncherWidgetProvider.FLAG_UPDATE_PHONE_STATE == intent
				.getFlags()) {
			if (isMobileDataEnabled) {
				Log.i("MLauncherActivity.onCreate()", "Disabling mobile data");
				manager.setMobileDataEnabled(false);
				isMobileDataEnabled = false;
			} else {
				Log.i("MLauncherActivity.onCreate()", "Enabling mobile data");
				manager.setMobileDataEnabled(true);
				isMobileDataEnabled = true;
			}
		}
		return isMobileDataEnabled;
	}

}
